#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <error.h>
#include <unistd.h>
#include <string>
using namespace std;
#include <stdio.h>
#include <cstring>

#define BUFFERSIZE 32

/* 命令行参数
    argc:表示命令行参数的个数
    argv[]:表示命令行参数的字段
*/
int main(int argc, char *argv[])
{
    // cout << "argc:" << argc << endl;
    // for (int idx = 0; idx < argc; idx++)
    // {
    //     printf("argc[%d] = %s\n",idx,argv[idx]);
    // }

    /* 检查命令行参数的个数 */
    if (argc != 3)
    {
        cout << "argument cnt error." << endl;
    }

    const char *srcFile = argv[1];
    const char *dstFile = argv[2];

    int srcFd = open(srcFile, O_RDONLY);
    if (srcFd == -1)
    {
        perror("src file open error:");
        exit(-1);
    }

    /* 权限 */
    /* access函数只能够判断文件是否包含某种权限，但是并不能够深入用户组内，必须开root权限执行代码 */
    int permission = 0;
    access(srcFile, R_OK) == 0 ? permission |= R_OK : permission;
    access(srcFile, W_OK) == 0 ? permission |= W_OK : permission;
    access(srcFile, X_OK) == 0 ? permission |= X_OK : permission;

    /* ??? todo... */
    /* 打开目标文件 */
    int dstFd = open(dstFile, O_WRONLY | O_CREAT, permission); // todo...

    if (dstFd == -1)
    {
        perror("dst file open error:");
        exit(-1);
    }

    char buffer[BUFFERSIZE + 1] = {0}; // +1 :留一个结束赋
    int readBytes = 0;
    while (1)
    {
        readBytes = read(srcFd, buffer, BUFFERSIZE);
        if (readBytes < BUFFERSIZE)
        {
            write(dstFd, buffer, readBytes);
            break;
        }
        else
        {
            write(dstFd, buffer, readBytes);
        }
        memset(buffer, 0, sizeof(buffer));
    }

    /* 关闭文件 */
    close(srcFd);
    close(dstFd);
    return 0;
}
